package com.demo.spring.tools;

import java.time.Duration;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;

@Repository
public class RedisChatMemoryStore implements ChatMemoryStore {
	
	// 注入RedisTemplate
	@Autowired
	private StringRedisTemplate redisTemplate;

	public List<ChatMessage> getMessages(Object memoryId) {
		String json = redisTemplate.opsForValue().get(memoryId.toString());
		return ChatMessageDeserializer.messagesFromJson(json);
	}

	public void updateMessages(Object memoryId, List<ChatMessage> messages) {
		String json = ChatMessageSerializer.messagesToJson(messages);
		redisTemplate.opsForValue().set(memoryId.toString(), json, Duration.ofDays(1));
	}

	public void deleteMessages(Object memoryId) {
		redisTemplate.delete(memoryId.toString());
	}

}
